import Vue from "vue";
import axios from 'axios';
import store from '../store/index';
//Vue.prototype.$ajax = axios;
//http://www.tuicool.com/articles/eMb2yuY
var ajax={
    get(url,data,json){
        url=ajax.seturl(url);
        var get=axios.get(url,data,{
            responseType:json || 'json',
            transformResponse:[function(data){
                if(data.errorCode==60){
                    store.commit('SETAGAINLOGIN',true)
                }
                return data;
            }]
        })
        return get;
    },post(url,data,json){
        var that=this;
        url=ajax.seturl(url);
        var post= axios.post(url,data,{
            headers: {'X-Requested-With': 'XMLHttpRequest'},
            responseType:json || 'json',
            transformResponse:[function(data){
                if(data.errorCode==60){
                    store.commit('SETAGAINLOGIN',true);
                    Vue.storage.removeItem('user')
                }
                return data;
            }]
        });
        return post;
    },seturl(url){
        var token=store.state.user.token || '';
        if(token==''){
            store.commit('SETAGAINLOGIN',true)
        }
        if(url.indexOf('?')>-1){
            return url+'&access_token='+token;
        }else{
            return url+'?access_token='+token;
        }
    }
}
Vue.prototype.$ajax=ajax;